﻿using System;
using System.Collections.Generic;
using System.Linq;
using Devbridge.IPolice.DataContracts;
using Devbridge.IPolice.DomainModel;
using Devbridge.IPolice.Repositories;
using Devbridge.IPolice.ServiceContracts;

namespace Devbridge.IPolice.Services
{
    public class PoliceOfficerService : IPoliceOfficerService
    {
        private IPoliceOfficerRepository policeRepository;

        public PoliceOfficerService()
        {
            policeRepository = new PoliceOfficerRepository();
        }

        public void RemovePoliceOfficerById(int id)
        {
           // var officer = policeRepository.GetById(id);

            policeRepository.Remove<PoliceOfficer>(id);
        }

        public IList<PoliceOfficer> GetPoliceOfficers(string firstName = null)
        {
            IQueryable<PoliceOfficer> query = policeRepository.AllQuery();

            if (!string.IsNullOrEmpty(firstName))
            {
                query = query.Where(x => x.FirstName == firstName);
            }

            return query.ToList();
        }

        public void AddPoliceOfficer(PoliceOfficer policeOfficer)
        {
            policeRepository.Save(policeOfficer);
        }

        public void RemovePoliceOfficerByLastName(string lastName)
        {
            if (string.IsNullOrEmpty(lastName))
            {
                throw new ArgumentException("Argument lastName must have value.");
            }

            IQueryable<PoliceOfficer> query = policeRepository.AllQuery();
            query = query.Where(x => x.LastName == lastName);

            PoliceOfficer officerToRemove = query.FirstOrDefault();

            if (officerToRemove != null)
            {
                policeRepository.Remove(officerToRemove);
            }
        }

        public void UpdatePhoneNumberForAll()
        {
            var all = policeRepository.AllQuery().ToList();
            foreach (var policeOfficer in all)
            {
                policeOfficer.PhoneNumber = "118";
                policeRepository.Save(policeOfficer);
            }
        }

        public IList<PoliceOfficer> GetPoliceOfficerWithCrimes()
        {
            var query = policeRepository.AllQuery();

            query = query.Where(policeOfficer => policeOfficer.Crimes.Count() > 0);

            var policeOfficers = query.ToList();

            return policeOfficers;
        }

        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        /// <filterpriority>2</filterpriority>
        public void Dispose()
        {
            policeRepository.Dispose();
        }        
    }
}